import { pages, subPackages, tabBar } from '@/pages.json'
import { isMp } from './platform'
import { Main } from '@/service/types'
import { enumParams } from '@/enum'
import { useCommonStore } from '@/store'

const getLastPage = () => {
  // getCurrentPages() 至少有1个元素，所以不再额外判断
  // const lastPage = getCurrentPages().at(-1)
  // 上面那个在低版本安卓中打包回报错，所以改用下面这个【虽然我加了src/interceptions/prototype.ts，但依然报错】
  const pages = getCurrentPages()
  return pages[pages.length - 1]
}

/** 判断当前页面是否是tabbar页  */
export const getIsTabbar = () => {
  if (!tabBar) {
    return false
  }
  if (!tabBar.list.length) {
    // 通常有tabBar的话，list不能有空，且至少有2个元素，这里其实不用处理
    return false
  }
  const lastPage = getLastPage()
  const currPath = lastPage.route
  return !!tabBar.list.find((e) => e.pagePath === currPath)
}

/**
 * 获取当前页面路由的 path 路径和 redirectPath 路径
 * path 如 ‘/pages/login/index’
 * redirectPath 如 ‘/pages/demo/base/route-interceptor’
 */
export const currRoute = () => {
  const lastPage = getLastPage()
  const currRoute = (lastPage as any).$page
  // console.log('lastPage.$page:', currRoute)
  // console.log('lastPage.$page.fullpath:', currRoute.fullPath)
  // console.log('lastPage.$page.options:', currRoute.options)
  // console.log('lastPage.options:', (lastPage as any).options)
  // 经过多端测试，只有 fullPath 靠谱，其他都不靠谱
  const { fullPath } = currRoute as { fullPath: string }
  // console.log(fullPath)
  // eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)
  // eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)
  return getUrlObj(fullPath)
}

const ensureDecodeURIComponent = (url: string) => {
  if (url.startsWith('%')) {
    return ensureDecodeURIComponent(decodeURIComponent(url))
  }
  return url
}
/**
 * 解析 url 得到 path 和 query
 * 比如输入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor
 * 输出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}
 */
export const getUrlObj = (url: string) => {
  const [path, queryStr] = url.split('?')
  // console.log(path, queryStr)

  if (!queryStr) {
    return {
      path,
      query: {},
    }
  }
  const query: Record<string, string> = {}
  queryStr.split('&').forEach((item) => {
    const [key, value] = item.split('=')
    // console.log(key, value)
    query[key] = ensureDecodeURIComponent(value) // 这里需要统一 decodeURIComponent 一下，可以兼容h5和微信y
  })
  return { path, query }
}
/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 这里设计得通用一点，可以传递key作为判断依据，默认是 needLogin, 与 route-block 配对使用
 * 如果没有传 key，则表示所有的pages，如果传递了 key, 则表示通过 key 过滤
 */
export const getAllPages = (key = 'needLogin') => {
  // 这里处理主包
  const mainPages = [
    ...pages
      .filter((page) => !key || page[key])
      .map((page) => ({
        ...page,
        path: `/${page.path}`,
      })),
  ]
  // 这里处理分包
  const subPages: any[] = []
  subPackages.forEach((subPageObj) => {
    // console.log(subPageObj)
    const { root } = subPageObj

    subPageObj.pages
      .filter((page) => !key || page[key])
      .forEach((page: { path: string } & Record<string, any>) => {
        subPages.push({
          ...page,
          path: `/${root}/${page.path}`,
        })
      })
  })
  const result = [...mainPages, ...subPages]
  // console.log(`getAllPages by ${key} result: `, result)
  return result
}

/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 只得到 path 数组
 */
export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((page) => page.path)

/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 只得到 path 数组
 */
export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)

/**
 * 根据微信小程序当前环境，判断应该获取的BaseUrl
 */
export const getEvnBaseUrl = () => {
  // 请求基准地址
  let baseUrl = import.meta.env.VITE_SERVER_BASEURL

  // 小程序端环境区分
  if (isMp) {
    const {
      miniProgram: { envVersion },
    } = uni.getAccountInfoSync()

    switch (envVersion) {
      case 'develop':
        baseUrl = 'https://api.fytxcq.cn'
        break
      case 'trial':
        baseUrl = 'https://api.fytxcq.cn'
        break
      case 'release':
        baseUrl = 'https://api.fytxcq.cn'
        break
    }
  }

  return baseUrl
}

/**
 * 根据微信小程序当前环境，判断应该获取的UPLOAD_BASEURL
 */
export const getEvnBaseUploadUrl = (url = '/file-info') => {
  // 请求基准地址
  let baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL

  // 小程序端环境区分
  if (isMp) {
    const {
      miniProgram: { envVersion },
    } = uni.getAccountInfoSync()

    switch (envVersion) {
      case 'develop':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
      case 'trial':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
      case 'release':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
    }
  }

  return baseUploadUrl
}

/**
 * 根据微信小程序当前环境，判断应该获取的UPLOAD_BASEURL
 */
export const getEvnFileUploadUrl = (url = '/personal-imagery-info/addPersonalImageryInfo') => {
  // 请求基准地址
  let baseUploadUrl = import.meta.env.VITE_UPLOAD_PERSONAL_BASEURL

  // 小程序端环境区分
  if (isMp) {
    const {
      miniProgram: { envVersion },
    } = uni.getAccountInfoSync()

    switch (envVersion) {
      case 'develop':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
      case 'trial':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
      case 'release':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
    }
  }

  return baseUploadUrl
}

/**
 * 根据微信小程序当前环境，判断应该获取的UPLOAD_BASEURL
 */
export const getEvnAvatarUploadUrl = (url = '/user-info/addAvatar') => {
  // 请求基准地址
  let baseUploadUrl = import.meta.env.VITE_UPLOAD_AVATAR_BASEURL

  // 小程序端环境区分
  if (isMp) {
    const {
      miniProgram: { envVersion },
    } = uni.getAccountInfoSync()

    switch (envVersion) {
      case 'develop':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
      case 'trial':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
      case 'release':
        baseUploadUrl = 'https://api.fytxcq.cn' + url
        break
    }
  }

  return baseUploadUrl
}

/**
 * 等待函数
 * @param time 毫秒
 * @returns 
 */
export const sleep = (time: number): Promise<void> => {
  return new Promise(resolve => setTimeout(resolve, time));
}

/**
 * 格式化的日期
 * @param date 需要格式化的日期对象
 * @returns 
 */
export const formatDate = (date: Date, type = 'YYYY-MM-DD HH:mm:ss'): string => {
  if (!date) return '--';
  const year = date.getFullYear();
  if (!year) return '--';
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  if (type === 'YYYY-MM-DD') {
    return `${year}-${month}-${day}`;
  }

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


export const formatDate2 = (dateStr: string, type = 'YYYY-MM-DD HH:mm:ss'): string => {
  if (!dateStr) return '--';
  const _dateStr = dateStr.split('-').join('/');
  const date = new Date(_dateStr);
  const year = date.getFullYear();
  if (!year) return '--';
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  if (type === 'YYYY-MM-DD') {
    return `${year}-${month}-${day}`;
  }

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * @description: 将扁平数组转化为树
 * @param {array} nodes 节点数组
 * @param {string} id 节点的id字段，默认为id
 * @param {string} pid 节点的父节点id字段，默认为pid
 * @param {string} children 节点的子节点字段，默认为children
 * @return {array} 树或森林
 */
export const generateTree = (
  nodes: Main.RegionInfo[], 
  id = 'id', 
  pid = 'parentId', 
  children = 'children'
): Main.RegionInfo[] => {
  if (!Array.isArray(nodes)) {
    return [];
  }

  const tree = [];
  const treeMap = {};

  for (const node of nodes) {
    treeMap[node[id]] = node;
  }

  for (const node of nodes) {
    const pNode = treeMap[node[pid]];

    if (pNode) {
      (pNode[children] || (pNode[children] = [])).push(node);
    } else {
      tree.push(node);
    }
  }

  return tree;
}

/**
 * 根据生日计算精确年龄（支持闰年和边界日期）
 * @param birthdate 格式应为YYYY-MM-DD或Date可解析的格式
 * @returns 年龄(数字)或'--'(无效输入)
 */
export const calculateAge = (birthdate: string): number | string => {
  // 输入校验
  if (!birthdate || typeof birthdate !== 'string') return '--';
  
  const birthDate = new Date(birthdate);
  const today = new Date();
  
  // 日期有效性检查
  if (isNaN(birthDate.getTime())) return '--';
  
  // 计算基准年龄
  let age = today.getFullYear() - birthDate.getFullYear();
  
  // 精确日期比较
  const hasBirthdayPassed = 
    today.getMonth() > birthDate.getMonth() ||
    (today.getMonth() === birthDate.getMonth() && 
     today.getDate() >= birthDate.getDate());
  
  if (!hasBirthdayPassed) age--;
  
  // 处理未来日期（年龄不可能为负数）
  return age < 0 ? 0 : age;
}

// 返回
export const back = () => {
  // 获取当前页面栈
  const pages = getCurrentPages();
  // 获取当前页面的实例
  const currentPage = pages[pages.length - 1];
  // 判断当前页面是否是栈中的第一个页面
  const isFirstPage = currentPage === pages[0];

  // 如果当前页面是第一个页面，则无法后退
  if (isFirstPage) {
    // 处理无法后退的情况
    uni.reLaunch({ url: '/pages/tabbar/index' });
  } else {
    // 可以执行后退操作
    uni.navigateBack();
  }
}

/**
 * 将数组分块
 * @param array 数组
 * @param size 分块数量
 * @returns [[],[]] 二维数组
 */
export function chunkArray<T>(array: T[], size: number): T[][] {
  return array.reduce((acc, val, i) => {
      if (i % size === 0) acc.push([val]);
      else acc[acc.length - 1].push(val);
      return acc;
  }, [] as T[][]);
}

export const getActions = computed(() => {
  const common = useCommonStore();
  const list = [
    { name: '乐缘币支付', type: 'balance' },
    { name: '微信支付', type: 'wechat' }
  ]
  // if (common.chargeConfig.typeName !== 'true') {
  //   list.length = 1;
  // }
  return list
})

/** 判断是否为iOS设备 */
export const isIOS = () => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync();
  if (!systemInfo) return false;
  // 判断是否为iOS设备
  return systemInfo.platform == 'ios' || systemInfo.system.indexOf('iOS') >= 0;
}

/** 获取回填省市区 */
export const getCityName = (data) => {
  const { provinceName, cityName, districtName } = data || {};
  let _cityStr = '';
  if (provinceName) {
    _cityStr += provinceName;
  }
  if (cityName) {
    _cityStr += (provinceName === cityName ? '' : cityName);
  }
  if (districtName) {
    _cityStr += districtName;
  }
  return _cityStr
}

/** 判断是否tabbar页面 */
export function isTabBarPage() {
  let pages: any = getCurrentPages();
  let currentPage = pages[pages.length - 1] || {};
  if (!currentPage.route) return false;
  return currentPage.route.indexOf('/tabbar') !== -1;
}

/** 上传文件 */
export function comUploadFile<T>(options: any) {
  const { 
    url = '/aliyun/imgae/auditImageFile', 
    tempFilePath, 
    formData 
  } = options || {};
  return new Promise<any>((resolve, reject) => {
    uni.uploadFile({
      url: 'https://api.fytxcq.cn' + url,
      filePath: tempFilePath,
      name: 'file',
      formData,
      success: (res) => {
        const data = res.data ? JSON.parse(res.data) : {};
        resolve(data);
      },
      fail:(fail)=>{
        reject(fail);
      },
    })
  })
}

/** 校验图片 */
export const checkImg = async(tempFile?: any) => {
  uni.showLoading({
    icon: 'none',
    title:'正在校验图片',
  })
  const res = await comUploadFile({ 
    tempFilePath: tempFile,
  })
  uni.hideLoading();
  const _data = res.data || {};
  if (!_data.approved) {
    uni.showToast({
      icon: 'none',
      title: `上传失败，原因："${_data.detailName}"`
    });
  }
  return _data.approved;
}

/** base64转换临时路径 */
export const base64ToTempPath = async(base64Data?: any) => {
  const fs = uni.getFileSystemManager()
  const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.jpg`
  fs.writeFileSync(tempFilePath, base64Data, 'base64')
  return tempFilePath;
}